package com.maikang.exammall.api;

import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.util.SignUtils;
import com.maikang.exammall.service.BillService;
import com.maikang.exammall.util.XMLUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequiredArgsConstructor
@Log4j2
public class PaymentController {

//    private final WxPayConfig payConfig;
    private final WxPayService payService;
    private final BillService billService;

    @PostMapping("/wx/wechat_callback")
    public String wechatPayCallbackNotify(HttpServletRequest request) {
        final String ackSuccessResponse = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[ok]]></return_msg></xml>";
        final String failToCheckSignatureResponse = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[check signature FAIL]]></return_msg></xml>";
        final String failToCheckCodeResponse = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[result_code is FAIL]]></return_msg></xml>";
        final String generalFailResponse = "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[result_code is FAIL]]></return_msg></xml>";
        try {
            synchronized (this) {
                Map<String, String> kvm = XMLUtil.parseRequestXmlToMap(request);
                log.info("wechat_callback is invoking... requestBody: {}", kvm);
                if (!SignUtils.checkSign(kvm, null, payService.getConfig().getMchKey())) {
                    log.error("out_trade_no: " + kvm.get("out_trade_no") + " check signature FAIL");
                    return failToCheckSignatureResponse;
                }
                if (!kvm.get("result_code").equals("SUCCESS")) {
                    log.error("out_trade_no: " + kvm.get("out_trade_no") + " result_code is FAIL");
                    return failToCheckCodeResponse;
                }

                // 处理业务逻辑
                boolean ok = billService.wechatPayCallback(kvm);
                if (ok) {
                    log.info("out_trade_no: " + kvm.get("out_trade_no") + " pay SUCCESS!");
                    return ackSuccessResponse;
                } else {
                    return generalFailResponse;
                }
            }
        } catch (Exception e) {
            log.error("failed to handle wechatCallback", e);
            return generalFailResponse;
        }
    }
}
